// 计算BMI
const calculateBMI = (weight, height) => {
  // 将身高从厘米转换为米
  const heightInMeters = height / 100;
  return (weight / (heightInMeters * heightInMeters)).toFixed(1);
};

// 获取BMI状态
const getBMIStatus = (bmi) => {
  if (bmi < 18.5) {
    return { text: "偏瘦", class: "status-warning" };
  } else if (bmi >= 18.5 && bmi < 24) {
    return { text: "正常", class: "status-normal" };
  } else if (bmi >= 24 && bmi < 28) {
    return { text: "超重", class: "status-warning" };
  } else {
    return { text: "肥胖", class: "status-warning" };
  }
};

// 计算基础代谢率（BMR）
const calculateBMR = (weight, height, age, gender) => {
  // 使用修正的Harris-Benedict公式
  if (gender === "1") {
    // 男性
    return Math.round(13.7 * weight + 5.0 * height - 6.8 * age + 66);
  } else {
    // 女性
    return Math.round(9.6 * weight + 1.8 * height - 4.7 * age + 655);
  }
};

// 计算每日推荐摄入量
const calculateDailyIntake = (bmr, activityLevel, dietPreference) => {
  // 活动水平系数
  const activityFactors = {
    1: 1.2, // 久坐不动
    2: 1.375, // 轻度活动
    3: 1.55, // 中度活动
    4: 1.725, // 重度活动
    5: 1.9, // 极重度活动
  };

  // 饮食偏好调整系数
  const dietFactors = {
    1: 1.0, // 标准饮食
    2: 0.8, // 减重
    3: 1.2, // 增重
    4: 1.0, // 素食
    5: 1.0, // 无特殊偏好
  };

  // 计算总热量需求
  const activityFactor = activityFactors[activityLevel] || 1.2;
  const dietFactor = dietFactors[dietPreference] || 1.0;
  const totalCalories = Math.round(bmr * activityFactor * dietFactor);

  // 计算三大营养素比例
  return {
    calories: totalCalories,
    protein: Math.round((totalCalories * 0.3) / 4), // 30%蛋白质，1g蛋白质=4卡路里
    carbs: Math.round((totalCalories * 0.4) / 4), // 40%碳水，1g碳水=4卡路里
    fat: Math.round((totalCalories * 0.3) / 9), // 30%脂肪，1g脂肪=9卡路里
    bmr: bmr,
  };
};

// 根据用户的BMI和饮食偏好生成套餐推荐
const generateMealRecommendations = (bmi, dailyIntake, dietPreference) => {
  // 根据BMI和饮食偏好调整套餐特点
  const getMealFeatures = () => {
    if (bmi < 18.5) {
      return {
        focus: "增重",
        features: ["高蛋白", "高热量", "营养密度高"],
      };
    } else if (bmi >= 24) {
      return {
        focus: "减重",
        features: ["低脂", "低热量", "高饱腹感"],
      };
    } else {
      return {
        focus: "均衡",
        features: ["营养均衡", "适中热量", "多样化"],
      };
    }
  };

  const { focus, features } = getMealFeatures();

  // 早餐套餐（占每日总热量的30%）
  const breakfastCalories = Math.round(dailyIntake.calories * 0.3);
  const breakfast = [
    {
      id: "b1",
      name: `${focus}营养早餐A`,
      image: "/images/meals/breakfast1.png",
      description: `${features[0]}的健康早餐组合，提供充足能量`,
      calories: Math.round(breakfastCalories * 0.9),
      price: 29.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.3),
        carbs: Math.round(dailyIntake.carbs * 0.3),
        fat: Math.round(dailyIntake.fat * 0.3),
      },
      type: "breakfast",
    },
    {
      id: "b2",
      name: `${focus}营养早餐B`,
      image: "/images/meals/breakfast2.png",
      description: `${features[1]}的清爽早餐，补充必需营养`,
      calories: Math.round(breakfastCalories * 0.8),
      price: 25.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.25),
        carbs: Math.round(dailyIntake.carbs * 0.3),
        fat: Math.round(dailyIntake.fat * 0.25),
      },
      type: "breakfast",
    },
    {
      id: "b3",
      name: `${focus}营养早餐C`,
      image: "/images/meals/breakfast3.png",
      description: `${features[2]}的活力早餐，开启美好一天`,
      calories: Math.round(breakfastCalories * 0.85),
      price: 27.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.28),
        carbs: Math.round(dailyIntake.carbs * 0.28),
        fat: Math.round(dailyIntake.fat * 0.28),
      },
      type: "breakfast",
    },
  ];

  // 午餐套餐（占每日总热量的40%）
  const lunchCalories = Math.round(dailyIntake.calories * 0.4);
  const lunch = [
    {
      id: "l1",
      name: `${focus}营养午餐A`,
      image: "/images/meals/lunch1.png",
      description: `${features[0]}的午间能量套餐，保持活力`,
      calories: Math.round(lunchCalories * 0.95),
      price: 39.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.4),
        carbs: Math.round(dailyIntake.carbs * 0.4),
        fat: Math.round(dailyIntake.fat * 0.4),
      },
      type: "lunch",
    },
    {
      id: "l2",
      name: `${focus}营养午餐B`,
      image: "/images/meals/lunch2.png",
      description: `${features[1]}的商务午餐，营养美味`,
      calories: Math.round(lunchCalories * 0.85),
      price: 35.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.35),
        carbs: Math.round(dailyIntake.carbs * 0.35),
        fat: Math.round(dailyIntake.fat * 0.35),
      },
      type: "lunch",
    },
    {
      id: "l3",
      name: `${focus}营养午餐C`,
      image: "/images/meals/lunch3.png",
      description: `${features[2]}的轻食午餐，健康美味`,
      calories: Math.round(lunchCalories * 0.9),
      price: 37.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.38),
        carbs: Math.round(dailyIntake.carbs * 0.38),
        fat: Math.round(dailyIntake.fat * 0.38),
      },
      type: "lunch",
    },
  ];

  // 晚餐套餐（占每日总热量的30%）
  const dinnerCalories = Math.round(dailyIntake.calories * 0.3);
  const dinner = [
    {
      id: "d1",
      name: `${focus}营养晚餐A`,
      image: "/images/meals/dinner1.png",
      description: `${features[0]}的晚间营养套餐，易消化`,
      calories: Math.round(dinnerCalories * 0.9),
      price: 36.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.3),
        carbs: Math.round(dailyIntake.carbs * 0.3),
        fat: Math.round(dailyIntake.fat * 0.3),
      },
      type: "dinner",
    },
    {
      id: "d2",
      name: `${focus}营养晚餐B`,
      image: "/images/meals/dinner2.png",
      description: `${features[1]}的清淡晚餐，助眠养胃`,
      calories: Math.round(dinnerCalories * 0.85),
      price: 33.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.28),
        carbs: Math.round(dailyIntake.carbs * 0.28),
        fat: Math.round(dailyIntake.fat * 0.28),
      },
      type: "dinner",
    },
    {
      id: "d3",
      name: `${focus}营养晚餐C`,
      image: "/images/meals/dinner3.png",
      description: `${features[2]}的家常晚餐，温暖美味`,
      calories: Math.round(dinnerCalories * 0.88),
      price: 34.9,
      nutrition: {
        protein: Math.round(dailyIntake.protein * 0.29),
        carbs: Math.round(dailyIntake.carbs * 0.29),
        fat: Math.round(dailyIntake.fat * 0.29),
      },
      type: "dinner",
    },
  ];

  return {
    breakfast,
    lunch,
    dinner,
  };
};

// 根据用户信息生成个性化营养建议
const generateNutritionTips = (bmi, dietPreference, activityLevel) => {
  const tips = [];

  // 基于BMI的建议
  if (bmi < 18.5) {
    tips.push({
      id: 1,
      icon: "/images/nutrition.png",
      title: "增加蛋白质摄入",
      content: "建议多食用瘦肉、鱼类、蛋类等优质蛋白，帮助增重和肌肉生长",
      recommendations: [
        "每天摄入1.6-2.0克/公斤体重的蛋白质",
        "优先选择瘦肉、鱼类、鸡蛋等优质蛋白",
        "适量补充乳制品",
        "餐后可以适当补充蛋白质奶昔",
      ],
      benefits: ["促进肌肉生长", "增强体质", "改善代谢", "帮助健康增重"],
      notes: [
        "增加蛋白质的同时要注意营养均衡",
        "建议搭配适量运动",
        "避免一次性摄入过多",
        "注意补充足够的水分",
      ],
    });
  } else if (bmi >= 24) {
    tips.push({
      id: 1,
      icon: "/images/nutrition.png",
      title: "控制热量摄入",
      content: "建议选择低脂、高纤维食物，控制每餐份量，避免暴饮暴食",
      recommendations: [
        "选择全谷物、蔬菜等高纤维食物",
        "控制每餐食物份量",
        "避免高糖、高脂食物",
        "保持规律的进餐时间",
      ],
      benefits: ["帮助控制体重", "改善血糖水平", "增加饱腹感", "促进新陈代谢"],
      notes: [
        "不建议极端节食",
        "保持适度运动",
        "注意补充必需营养",
        "保持良好的作息时间",
      ],
    });
  }

  // 基于活动水平的建议
  if (activityLevel <= 2) {
    tips.push({
      id: 2,
      icon: "/images/nutrition.png",
      title: "增加运动量",
      content: "建议每天进行30分钟以上中等强度运动，提高基础代谢",
      recommendations: [
        "每天步行30分钟以上",
        "可以选择游泳、骑车等有氧运动",
        "适当进行力量训练",
        "保持运动的规律性",
      ],
      benefits: [
        "提高基础代谢率",
        "改善心肺功能",
        "增强肌肉力量",
        "帮助控制体重",
      ],
      notes: [
        "运动前要充分热身",
        "循序渐进，不要过度运动",
        "注意补充水分",
        "如有不适及时停止",
      ],
    });
  } else {
    tips.push({
      id: 2,
      icon: "/images/nutrition.png",
      title: "注意运动恢复",
      content: "运动后及时补充蛋白质和碳水，帮助肌肉恢复和能量补充",
      recommendations: [
        "运动后30分钟内补充蛋白质",
        "适量补充碳水化合物",
        "保证充足的休息时间",
        "注意肌肉放松和拉伸",
      ],
      benefits: [
        "促进肌肉恢复",
        "补充能量消耗",
        "预防运动损伤",
        "提高训练效果",
      ],
      notes: [
        "避免过度训练",
        "保证充足的睡眠",
        "注意营养均衡",
        "听从身体反馈适时调整",
      ],
    });
  }

  // 基于饮食偏好的建议
  if (dietPreference === 2) {
    // 减重
    tips.push({
      id: 3,
      icon: "/images/nutrition.png",
      title: "合理安排餐点",
      content: "建议少食多餐，保持每餐间隔3-4小时，避免夜间进食",
      recommendations: [
        "每天保持4-5餐",
        "控制每餐份量",
        "晚餐不要太晚",
        "可以适当加餐但注意总热量",
      ],
      benefits: ["稳定血糖水平", "控制食欲", "提高代谢效率", "帮助减重"],
      notes: [
        "注意记录每餐热量",
        "保持规律的作息",
        "避免情绪性饮食",
        "保持充足的水分摄入",
      ],
    });
  } else if (dietPreference === 3) {
    // 增重
    tips.push({
      id: 3,
      icon: "/images/nutrition.png",
      title: "营养密度",
      content: "选择营养密度高的食物，适当增加健康脂肪的摄入",
      recommendations: [
        "选择全脂乳制品",
        "适量食用坚果",
        "增加优质蛋白摄入",
        "合理搭配碳水化合物",
      ],
      benefits: ["提供充足能量", "促进肌肉生长", "补充必需营养", "健康增重"],
      notes: [
        "避免垃圾食品",
        "注意营养均衡",
        "配合适度运动",
        "循序渐进增加摄入",
      ],
    });
  }

  // 通用建议
  tips.push({
    id: 4,
    icon: "/images/nutrition.png",
    title: "充足饮水",
    content: "每天饮水2000-2500ml，保持良好的代谢状态",
    recommendations: [
      "每天至少饮用8杯水",
      "运动时补充更多水分",
      "可以喝温水或白开水",
      "避免含糖饮料",
    ],
    benefits: ["促进新陈代谢", "改善消化功能", "维持体温平衡", "预防脱水"],
    notes: [
      "不要一次饮用太多水",
      "餐前餐后适量饮水",
      "注意补充电解质",
      "根据天气和运动量调整",
    ],
  });

  return tips;
};

// 根据当前营养提示生成相关推荐
const generateRelatedTips = (currentTip) => {
  // 示例相关营养提示数据
  const relatedTipsData = [
    {
      id: 101,
      title: "蛋白质与肌肉恢复",
      brief: "了解如何通过优质蛋白质摄入促进运动后的肌肉恢复",
      image: "/images/nutrition.png",
      date: "2023-05-15"
    },
    {
      id: 102,
      title: "健康碳水化合物选择",
      brief: "如何选择优质碳水化合物，避免血糖波动",
      image: "/images/nutrition.png",
      date: "2023-06-10"
    },
    {
      id: 103,
      title: "好脂肪vs坏脂肪",
      brief: "分辨健康与不健康脂肪，合理安排饮食",
      image: "/images/nutrition.png",
      date: "2023-07-05"
    },
    {
      id: 104,
      title: "科学饮水指南",
      brief: "每天应该喝多少水？什么时候喝最有效？",
      image: "/images/nutrition.png",
      date: "2023-08-20"
    },
    {
      id: 105,
      title: "膳食纤维的重要性",
      brief: "了解膳食纤维对肠道健康和减重的作用",
      image: "/images/nutrition.png",
      date: "2023-09-12"
    }
  ];
  
  // 过滤掉当前正在查看的提示（如果在列表中）
  const filteredTips = relatedTipsData.filter(tip => 
    !currentTip || tip.id !== currentTip.id
  );
  
  // 随机打乱顺序并返回前3条
  return filteredTips
    .sort(() => Math.random() - 0.5)
    .slice(0, 3);
};

// 导出所有函数
module.exports = {
  calculateBMI,
  getBMIStatus,
  calculateBMR,
  calculateDailyIntake,
  generateMealRecommendations,
  generateNutritionTips,
  generateRelatedTips,
};
